package com.tg.app.view;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tg.app.R;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.DeviceUIHelper;
import com.tange.base.toolkit.AppUtil;

public class CameraPlayerStatusView extends FrameLayout {
    public final static int STATUS_NONE = 0x000;
    public final static int STATUS_LOADING = 0x001;
    public final static int STATUS_ERROR_NETWORK_ERROR = 0x002;
    public final static int STATUS_ERROR_DEVICE_OFFLINE = 0x003;
    public final static int STATUS_ERROR_DEVICE_OFF = 0x004;
    public final static int STATUS_ERROR_DEVICE_SERVICE_EXPIRED = 0x005;
    public final static int STATUS_ERROR_SDCARD_NONE = 0x006;
    public final static int STATUS_ERROR_CLOUD_SERVICE_NONE = 0x007;
    public final static int STATUS_ERROR_SDCARD_OFFLINE = 0x008;
    public final static int STATUS_ERROR_SDCARD_DATA_NONE = 0x009;
    public final static int STATUS_ERROR_TIME_DATA_NONE = 0x00a;
    public final static int STATUS_ERROR_PLAY_END = 0x00b;
    public final static int STATUS_ERROR_DEVICE_SLEEP = 0x00c;
    public final static int STATUS_ERROR_CLOUD_DATA_NONE = 0x00d;
    public final static int STATUS_ERROR_CAR_LOCAL_NETWORK_ERROR = 0x00e;

    public final static int STATUS_ERROR_CAR_SERVICE_NONE = 0x00f;

    public final static int STATUS_ERROR_CAR_DATA_NONE = 16;
    public final static int STATUS_ERROR_CAR_PRIMARY = 17;
    public final static int STATUS_ERROR_FOREIGN_ICC_ID_NOTICE = 18;
    public final static int STATUS_ERROR_SDCARD_EXCEPTION = 19;
    public final static int STATUS_ERROR_CAR_PRIMARY_WATCH_END = 20;
    public final static int STATUS_ERROR_TIME_DATA_AI_NONE = 21;
    public final static int STATUS_ERROR_CLOUD_DATA_AI_NONE = 22;
    public final static int STATUS_ERROR_STUDY_SERVICE_NONE = 23;

    private static final int DURATION_TIME = 1000;
    private static final int RED_VALUE = 30;
    private static final int GREED_VALUE = 31;
    private static final int BLUE_VALUE = 36;
    private static final int FULL_ALPHA_VALUE = 255;
    private static final Float FULL_ALPHA_FLOAT_VALUE = 1f;
    private static final Float FULL_ALPHA_FLOAT_VALUE_1 = 0.6f;
    private static final Float FULL_ALPHA_FLOAT_VALUE_2 = 0.4f;
    private Button btnStatus;
    private Button btnReconnect;
    private TextView mErrorText;
    private TextView sleepText;
    private TextView localErrorText;
    private TextView loadingText;
    private LinearLayout loadingLayout, errorLayout;
    private ImageView loadingImage,errorAiImage;
    private int playerStatus;
    private RelativeLayout carLocalErrorLayout, statusRl;
    private Context mContext;
    private DeviceItem deviceItem;
    private DeviceUIHelper mDeviceUIHelper;
    private ImageView imageError;

    public void setDeviceUIHelper(DeviceUIHelper mDeviceUIHelper) {
        this.mDeviceUIHelper = mDeviceUIHelper;
    }

    private ACCameraPlayerView.ACCameraPlayerViewClickListener playerViewClickListener;

    public void setPlayerViewClickListener(ACCameraPlayerView.ACCameraPlayerViewClickListener playerViewClickListener) {
        this.playerViewClickListener = playerViewClickListener;
    }

    public void setDeviceItem(DeviceItem deviceItem) {
        this.deviceItem = deviceItem;
    }

    public CameraPlayerStatusView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public CameraPlayerStatusView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CameraPlayerStatusView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.camera_player_status, this);
        loadingText = view.findViewById(R.id.tv_camera_player_status_loading);
        statusRl = view.findViewById(R.id.rel_camera_player_status_status);
        loadingImage = view.findViewById(R.id.camera_player_status_loading);
        loadingLayout = view.findViewById(R.id.ll_camera_player_status_loading);
        errorLayout = view.findViewById(R.id.ll_camera_player_status_error);
        btnStatus = view.findViewById(R.id.btn_camera_player_status_status);
        mErrorText = view.findViewById(R.id.tv_camera_player_status_error);
        sleepText = view.findViewById(R.id.tv_camera_player_status_sleep);
        imageError = view.findViewById(R.id.image_error);
        btnReconnect = view.findViewById(R.id.btn_camera_player_status_reconnect);
        carLocalErrorLayout = view.findViewById(R.id.rel_car_local_error);
        localErrorText = view.findViewById(R.id.tv_car_local_error_des);
        errorAiImage =view.findViewById(R.id.iv_camera_player_status_error_ai);
        setListener(view);
    }

    private void setListener(View view) {
        Button btnReconnectLocal = view.findViewById(R.id.btn_camera_player_status_reconnect_local);
        Button btnSettingWifiLocal = view.findViewById(R.id.btn_camera_player_status_setting_wifi);
        btnStatus.setOnClickListener(v -> {
            if (playerViewClickListener != null) {
                switch (playerStatus){
                    case CameraPlayerStatusView.STATUS_ERROR_DEVICE_SERVICE_EXPIRED:
                    case CameraPlayerStatusView.STATUS_ERROR_CLOUD_SERVICE_NONE:
                    case CameraPlayerStatusView.STATUS_ERROR_CAR_PRIMARY:
                    case CameraPlayerStatusView.STATUS_ERROR_STUDY_SERVICE_NONE:
                    case CameraPlayerStatusView.STATUS_ERROR_CAR_PRIMARY_WATCH_END:
                        playerViewClickListener.onOpenServe();
                        break;
                    case CameraPlayerStatusView.STATUS_ERROR_NETWORK_ERROR:
                        playerViewClickListener.onHelpClick(true);
                        break;
                    case CameraPlayerStatusView.STATUS_ERROR_DEVICE_OFFLINE:
                        playerViewClickListener.onHelpClick(false);
                        break;
                    default:
                        mDeviceUIHelper.setClickOpenDeviceBtn(true);
                        playerViewClickListener.onDeviceOpenClick();
                        break;
                }
            }
        });
        OnClickListener reconnectListener = v -> {
            if (playerViewClickListener != null) {
                playerViewClickListener.onReconnectClick();
            }

        };
        btnReconnect.setOnClickListener(reconnectListener);
        btnReconnectLocal.setOnClickListener(reconnectListener);
        btnSettingWifiLocal.setOnClickListener(v -> {
            if (playerViewClickListener != null) {
                playerViewClickListener.onWifiSettings();
            }
        });
        setOnClickListener(v -> onShowNav(true));
    }

    public void setLoadingVisibility(int visible) {
        setLoadingVisibility(visible, null);
    }

    public void setLoadingVisibility(int visible, String text) {
        if (!AppUtil.isActivityFinishingOrDestroyed(mContext)) {
            if (DeviceHelper.isLockBell(deviceItem)){
                Glide.with(mContext).asGif().load(R.mipmap.icon_lockbell_camera_player_loading).into(loadingImage);
            }else{
                Glide.with(mContext).asGif().load(R.mipmap.icon_camera_player_loading).into(loadingImage);
            }

            setPlayerStatus(visible == View.GONE ? STATUS_NONE : STATUS_LOADING);
            if (visible == View.VISIBLE && !StringUtils.isEmpty(text)){
                setLoadingText(text);
            }
        }
    }

    public int getLoadingVisibility() {
        return loadingLayout.getVisibility();
    }

    public int getPlayerStatus() {
        return playerStatus;
    }

    public void setErrorText(String text) {
        mErrorText.setText(text);
        mErrorText.setVisibility(VISIBLE);
    }

    public void setLoadingText(String text){
        loadingText.setText(text);
    }

    public void setPlayerStatus(int status) {
        playerStatus = status;

        TGLog.d("Camera-log", "[setPlayerStatus:status] " + status);
        if (status == STATUS_NONE) {
            hideAllView();
            return;
        }

        if (status == STATUS_LOADING) {
            showLoadingView();
            return;
        }

        showErrorLayoutView();
        onShowNav(false);
        doShowStatus(status);
    }

    private void onShowNav(boolean b) {
        if (playerViewClickListener != null) {
            playerViewClickListener.onShowNav(b);
        }
    }

    private void showErrorLayoutView() {
        loadingLayout.setVisibility(GONE);
        statusRl.setBackgroundResource(R.color.camera_player_status_color);
        setVisibility(VISIBLE);
        errorLayout.setVisibility(VISIBLE);
        btnStatus.setVisibility(GONE);
        btnReconnect.setVisibility(GONE);
        sleepText.setVisibility(GONE);
        imageError.setVisibility(GONE);
        carLocalErrorLayout.setVisibility(GONE);
    }

    private void doShowStatus(int status) {
        int resId = 0;
        TGLog.d("Camera-log", "[status] " + status);
        switch (status) {
            case STATUS_ERROR_NETWORK_ERROR:
                resId = R.string.live_connection_error;
                btnStatus.setText(R.string.camera_play_error_help);
                btnReconnect.setVisibility(VISIBLE);
                btnStatus.setVisibility(VISIBLE);
                break;
            case STATUS_ERROR_DEVICE_OFFLINE:
                resId = R.string.live_offline;
                btnStatus.setVisibility(VISIBLE);
                btnStatus.setText(R.string.camera_play_error_help);
                break;
            case STATUS_ERROR_DEVICE_OFF:
                resId = R.string.camera_closed;
                btnStatus.setText(R.string.live_device_open);
                btnStatus.setVisibility(DeviceHelper.isShare(deviceItem)? GONE : VISIBLE);
                break;
            case STATUS_ERROR_DEVICE_SLEEP:
                resId = R.string.camera_device_sleep;
                sleepText.setVisibility(VISIBLE);
                break;
            case STATUS_ERROR_DEVICE_SERVICE_EXPIRED:
                resId = R.string.sim_service_expired;
                btnStatus.setVisibility(VISIBLE);
                btnStatus.setText(R.string.extended_use_device);
                break;
            case STATUS_ERROR_SDCARD_NONE:
            case STATUS_ERROR_SDCARD_OFFLINE:
                resId = R.string.playback_no_sd_card;
                break;
            case STATUS_ERROR_SDCARD_EXCEPTION:
                resId = R.string.playback_exception_sd_card;
                break;
            case STATUS_ERROR_SDCARD_DATA_NONE:
                resId = R.string.sd_playback_empty;
                break;
            case STATUS_ERROR_CAR_DATA_NONE:
            case STATUS_ERROR_CLOUD_DATA_NONE:
                resId = R.string.cloud_playback_empty;
                break;
            case STATUS_ERROR_CAR_SERVICE_NONE:
                resId = R.string.playback_car_service_disable;
                break;
            case STATUS_ERROR_CAR_PRIMARY:
                resId = R.string.playback_car_service_primary;
                btnStatus.setText(R.string.playback_car_service_upgrade);
                btnStatus.setVisibility(VISIBLE);
                break;
            case STATUS_ERROR_STUDY_SERVICE_NONE:
                resId = R.string.learning_services_notpurchased;
                sleepText.setText(R.string.lamp_study_service_tip);
                sleepText.setVisibility(VISIBLE);
                imageError.setVisibility(VISIBLE);
                btnStatus.setVisibility(GONE);
                break;
            case STATUS_ERROR_CLOUD_SERVICE_NONE:
                resId = R.string.playback_cloud_service_disable;
                btnStatus.setText(R.string.extended_use_device);
                btnStatus.setVisibility(VISIBLE);
                break;
            case STATUS_ERROR_TIME_DATA_NONE:
                resId = R.string.no_video_please_to_scroll;
                break;
            case STATUS_ERROR_PLAY_END:
                resId = R.string.the_video_is_finished;
                break;
            case STATUS_ERROR_FOREIGN_ICC_ID_NOTICE:
                resId = R.string.the_video_is_finished;
                break;
            case STATUS_ERROR_CAR_LOCAL_NETWORK_ERROR:
                carLocalErrorLayout.setVisibility(VISIBLE);
                String uuid = ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine();
                if (deviceItem != null) {
                    uuid +=  deviceItem.uuid;
                }
                String text = String.format(getResources().getString(R.string.car_local_des), uuid);
                localErrorText.setText(text);
                mErrorText.setVisibility(GONE);
                return;
            case STATUS_ERROR_CAR_PRIMARY_WATCH_END:
                resId = R.string.playback_car_service_primary_watch_end;
                btnStatus.setText(R.string.playback_car_service_upgrade);
                btnStatus.setVisibility(VISIBLE);
                break;

            case STATUS_ERROR_TIME_DATA_AI_NONE:
                errorAiImage.setVisibility(VISIBLE);
                resId = R.string.no_video_please_to_scroll_ai;
                break;
            case STATUS_ERROR_CLOUD_DATA_AI_NONE:
                resId = R.string.cloud_playback_ai_empty;
                errorAiImage.setVisibility(VISIBLE);
                break;
        }
        if (status!=STATUS_ERROR_TIME_DATA_AI_NONE&&status!=STATUS_ERROR_CLOUD_DATA_AI_NONE){
            errorAiImage.setVisibility(GONE);
        }

        if (resId > 0) {
            mErrorText.setText(resId);
            mErrorText.setVisibility(VISIBLE);
        }
    }

    private void showLoadingView() {
        if (loadingLayout.getVisibility() == GONE) {
            statusRl.setBackgroundResource(R.color.camera_player_status_color_gray);
            @SuppressLint("ObjectAnimatorBinding")
            ObjectAnimator alpha = ObjectAnimator.ofFloat(getBackground(), "alpha", FULL_ALPHA_FLOAT_VALUE, FULL_ALPHA_FLOAT_VALUE_1);
            alpha.addUpdateListener(valueAnimator -> {
                Float i = (Float) valueAnimator.getAnimatedValue();
                int a = (int) (i * FULL_ALPHA_VALUE);
                loadingLayout.setAlpha((FULL_ALPHA_FLOAT_VALUE - i) / FULL_ALPHA_FLOAT_VALUE_2);
                int color = Color.argb(a, RED_VALUE, GREED_VALUE, BLUE_VALUE);
                statusRl.setBackgroundColor(color);

            });
            alpha.setDuration(DURATION_TIME).start();
            setVisibility(VISIBLE);
            errorLayout.setVisibility(GONE);
            carLocalErrorLayout.setVisibility(GONE);
            loadingLayout.setVisibility(VISIBLE);
            onShowNav(true);
        }
    }

    private void hideAllView() {
        carLocalErrorLayout.setVisibility(GONE);
        loadingLayout.setVisibility(GONE);
        errorLayout.setVisibility(GONE);
        imageError.setVisibility(GONE);
        errorAiImage.setVisibility(GONE);
        setVisibility(GONE);
    }
}
